﻿/*
 * Created by SharpDevelop.
 * User: fred
 * Date: 19/03/2011
 * Time: 20:37
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Windows.Input;

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using MetaVideoEditorEvolved.Entity;
using MetaVideoEditorEvolved.Helper;
using MetaVideoEditorEvolved.Messages;
using MetaVideoEditorEvolved.UI;
using mveEngine;

namespace MetaVideoEditorEvolved.ViewModel
{
	/// <summary>
	/// Description of MultiAutoSearchVM.
	/// </summary>
	public class MultiAutoSearchVM : ViewModelBase
	{
		private ObservableCollection<MultiAutoSearchItem> items;
		private MultiAutoSearchItem selectedItem;
		private BackgroundWorker bwAutoSearch;
		private int progressBarValue,
		progressBarMaximum;
		private bool isComplete;
		
		public bool IsSave { get; set; }
		
		public MultiAutoSearchVM(List<MetaVideoEditorEvolved.UI.Entity.MediaItemBaseEntity> items, bool isSaveAction)
		{
			this.IsSave = isSaveAction;
			this.IsComplete = false;
			this.items = new ObservableCollection<MultiAutoSearchItem>(
				(from it in items
				 where it is MetaVideoEditorEvolved.UI.Entity.VideoMediaElement
				 select new MultiAutoSearchItem
				 {
				 	Status = ActionStatus.Uknown,
				 	Item = it as MetaVideoEditorEvolved.UI.Entity.VideoMediaElement
				 }).ToList());
			
			ProgressBarMaximum = this.items.Count;
			
			bwAutoSearch = new BackgroundWorker();
			bwAutoSearch.WorkerSupportsCancellation =  true;
			bwAutoSearch.WorkerReportsProgress = true;
			bwAutoSearch.RunWorkerCompleted+=(o1, args1)=>
			{
				this.IsComplete = true;
			};
			
			bwAutoSearch.ProgressChanged+=(o, args)=>
			{
				if(!isSaveAction)
				{
					var content = args.UserState as object[];
					MultiAutoSearchItem element = content[0] as MultiAutoSearchItem;
					var updated = content[1] as Item;
					
					if(updated!=null)
					{
						updated.CopyToMediaUiEntity(element.Item);
					}
					
					if(!element.Item.HasChanged)
					{
						element.Status = ActionStatus.Error;
						
						if (content.Count()>2) {
							element.ErrorDetail = content[2] as MetaVideoEditorEvolved.AddIn.Entity.InvalidPluginException;
						}
					}
					else
					{
						element.Status = ActionStatus.Success;
					}
					
					Messenger.Default.Send<Messages.MediaItemChanged>(new MediaItemChanged(element));
				}
				else
				{
					var element = args.UserState as MultiAutoSearchItem;
					element.Status = ActionStatus.Success;
					
					var mveItem = KernelSessionManager.SessionInstance.RealKernel.ItemCollection.ItemsList.First(i=>i.Id == element.Item.Id.ToString());
					mveItem.CopyToMediaUiEntity(element.Item);
					
					Messenger.Default.Send<Messages.MediaItemChanged>(new MediaItemChanged(element));
				}
				
				this.ProgressBarValue++;
			};
			
			bwAutoSearch.DoWork += (s, e) =>
			{
				foreach (var element in Items)
				{
					if(bwAutoSearch.CancellationPending == false)
					{
						if(!isSaveAction)
						{
							try
							{
								var updated = this.CreateKernelHelper().AutoSearchMediaItem(element.Item);
								this.CreateKernelHelper().SyncItemToEngine(updated);
								
								bwAutoSearch.ReportProgress(0,new object[] {element, updated});
							}
							catch (Exception ex)
							{
								bwAutoSearch.ReportProgress(0,new object[] {element, null, ex});
							}
						}
						else
						{
							var mveItem = KernelSessionManager.SessionInstance.RealKernel.ItemCollection.ItemsList.First(i=>i.Id == element.Item.Id.ToString());
							mveItem.IsInError = false;
							var changedPoster = from p in element.Item.Posters
								where p.IsDirty select p;
							
							foreach (var poster in changedPoster) {
								mveItem.ImagesPaths.First(p=>p.Image == poster.Image).Checked = poster.Checked;
							}
							
							this.CreateKernelHelper().SaveItem(element.Item);
							bwAutoSearch.ReportProgress(0, element);
						}
					}
					else
					{
						break;
					}
				}
			};
			
			DoubleClickListBox = new RelayCommand(() =>
			                                      {
			                                      	new Search()
			                                      	{
			                                      		DataContext = new SearchVM(SelectedItem.Item)
			                                      	}.ShowDialog();

			                                      	if(SelectedItem.Item.HasChanged)
			                                      	{
			                                      		SelectedItem.Status = ActionStatus.Success;
			                                      	}
			                                      },()=>
			                                      {
			                                      	return !isSaveAction && this.SelectedItem!=null;
			                                      }
			                                     );
			
			ClosingCommand = new RelayCommand(() =>
			                                  {
			                                  	if(bwAutoSearch != null)
			                                  	{
			                                  		bwAutoSearch.CancelAsync();
			                                  	}
			                                  });
			
			CloseCommand = new RelayCommand(() =>
			                                {
			                                	Messenger.Default.Send<CloseMessage>(new CloseMessage { WindowToClose = WindowType.MultiAutoSearch });
			                                });
			
			bwAutoSearch.RunWorkerAsync();
		}
		
		public ICommand DoubleClickListBox { get; set; }
		
		protected virtual Helper.IKernelHelper CreateKernelHelper()
		{
			return new Helper.KernelHelper();
		}
		
		public string ProgressValue
		{
			get
			{
				return string.Format("{0}/{1}", ProgressBarValue, ProgressBarMaximum);
			}
		}
		
		public bool IsComplete
		{
			get
			{
				return this.isComplete;
			}
			
			set
			{
				this.isComplete = value;
				this.RaisePropertyChanged("IsComplete");
			}
		}
		
		public int ProgressBarValue
		{
			get
			{
				return progressBarValue;
			}
			
			set
			{
				progressBarValue = value;
				RaisePropertyChanged("ProgressBarValue");
				RaisePropertyChanged("ProgressValue");
			}
		}
		
		public int ProgressBarMaximum
		{
			get
			{
				return progressBarMaximum;
			}
			
			set
			{
				progressBarMaximum = value;
				RaisePropertyChanged("ProgressBarMaximum");
				RaisePropertyChanged("ProgressValue");
			}
		}
		
		public ObservableCollection<MultiAutoSearchItem> Items
		{
			get
			{
				return items;
			}
			
			set
			{
				items = value;
				RaisePropertyChanged("Items");
			}
		}
		
		public MultiAutoSearchItem SelectedItem
		{
			get
			{
				return selectedItem;
			}
			
			set
			{
				selectedItem = value;
				RaisePropertyChanged("SelectedItem");
			}
		}
		
		public string TitleWindow
		{
			get
			{
				return Kernel.Instance.GetString("MultiAutoSearchTitle");
			}
		}
		
		public ICommand ClosingCommand { get; set; }
		public ICommand CloseCommand { get; set; }
	}
}
